﻿using System;

namespace OneWorks.Web.Common
{
    using System.Web;
    using OneWorks.Metadata.Entity;
    using OneWorks.Metadata.Enum;
    using OneWorks.Web.Common.Model;
    using OneWorks.Web.Extension;

    public class FileHandle
    {
        private readonly ImageHandle imageHandle = new ImageHandle();

        public RunResult<ImageModel> UploadImage(HttpPostedFileBase bagFile, ImageUse use)
        {
            RunResult<ImageModel> runResult = new RunResult<ImageModel>();
            try
            {
                UserContext userContext = new UserContext();
                if (!userContext.IsLogin)
                    return new RunResult<ImageModel>
                    {
                        Status = ResultStatus.Failure,
                        Message = "上传文件需要用户登录,请登录后上传."
                    };
                ImageModel model = new ImageModel
                                       {
                                           UserID = userContext.Current.UserCode
                                       };
                FileUploadHandler handler = new FileUploadHandler(Config.UPLOADIMAGE, bagFile);
                string filePath = handler.Save();
                if (filePath == null)
                {
                    return new RunResult<ImageModel>
                               {
                                   Status = ResultStatus.Failure,
                                   Message = "上传文件出现异常，返回上传文件物理路径不正确."
                               };
                }
                model.Path = filePath;
                System.Drawing.Image img = System.Drawing.Image.FromFile(model.Path);
                model.Height = img.Height;
                model.Width = img.Width;
                var extension = System.IO.Path.GetExtension(filePath);
                if (extension != null)
                {
                    model.ImgType = extension.Replace(".", "");
                }
                string fileName = System.IO.Path.GetFileName(filePath);
                string url = "http://" + HttpContext.Current.Request.Url.Host + "/" + handler.VirtualPath + "/" + fileName;
                model.Src = url;
                runResult = imageHandle.Add(model);

            }
            catch (Exception exception)
            {
                Utils.Log.LogHandler.Log.Error("上传文件出现异常", exception);
                runResult.Status = ResultStatus.Abnormal;
                runResult.Message = "上传文件出现异常";
                runResult.Exception = exception;
            }
            return runResult;
        }
    }
}
